package com.giggle.mybatis.algorithm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (取模分表)
 * @date 2020/8/31 15:57
 */
public class HashModTable {

    private static final Logger logger = LoggerFactory.getLogger(HashModTable.class);

    public HashModTable() {
    }

    public static String getSplitTableName(String tableName, Object splitKeyVal, Integer subTableCount) {
        if (splitKeyVal == null) {
            throw new RuntimeException("splitKeyVal is null.tableName:" + tableName);
        } else {
            long hashVal = (long)splitKeyVal.toString().hashCode();
            hashVal = hashVal * 2654435769L >> 28;
            hashVal = Math.abs(hashVal) % (long)subTableCount;
            String hashTableName = tableName + "_" + hashVal;
            if (logger.isDebugEnabled()) {
                logger.debug("used hash mod algorithm. build {}'s subtable name: {}. ", tableName, hashTableName);
            }

            return hashTableName;
        }
    }
}
